#!/bin/bash
#
# Create or update a stack.
#
# Before running this script update the 'user-data' and/or 'stack.json' files in this directory as appropriate.
#
# This script takes 2 parameters, in this order:
#
#   ./stack <create|update> <stack-name> <deployment-package-base-name>
#
# Once a stack has been updated, you may have to manually terminate/restart
# all instances in order for things like new instance user-data to actually
# be used.  The deployment-package-name is the name of the .tar.gz without .tar.gz on the end.
#

PACKAGE_NAME=$2
if [ -z "$2" ]
  then
    PACKAGE_NAME=$npm_package_name-$(git describe)
fi

echo "Deploying $PACKAGE_NAME"

aws s3 --profile $npm_package_config_awsProfile cp ../packages/$PACKAGE_NAME.tar.gz $npm_package_config_awsS3PackagesPath/$PACKAGE_NAME.tar.gz
if [[ $? -ne 0 ]]; then
    exit 1
fi

# encode the 'user-data' file into a BASE64 string (use Perl since the Linux(GNU)/OSX(BSD) 'base64' utils are different
BASE64_USERDATA=$(node createUserData.js user-data $PACKAGE_NAME)
echo "Length of the BASE64 encoded user-data is ${#BASE64_USERDATA} (max size allowed is 4096.)"

# run the AWS CloudFormation command to take action
aws cloudformation $1-stack \
    --profile $npm_package_config_awsProfile \
    --region $npm_package_config_awsRegion \
    --stack-name "$PACKAGE_NAME" \
    --template-body file://stack.json \
    --capabilities CAPABILITY_IAM \
    --parameters \
      ParameterKey=ImageId,ParameterValue="${npm_package_config_awsEc2ImageId}" \
      ParameterKey=InstanceType,ParameterValue="${npm_package_config_awsEc2InstanceType}" \
      ParameterKey=KeyName,ParameterValue="${npm_package_config_awsKeyName}" \
      ParameterKey=RootVolumeSize,ParameterValue='16' \
      ParameterKey=UserDataBase64,ParameterValue="${BASE64_USERDATA}" \
      # ParameterKey=SpotPrice,ParameterValue='0.041' \
